using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Algorithms;
using Algorithms.Numerical;
using Base;
using PetriDiagram;

namespace PetriDiagram.Algorithms
{
    public partial class SSAnalysisForm : Form
    {
        private PetriDocument document;
        public SSAnalysisForm(PetriDocument doc)
        {
            InitializeComponent();
            this.document = doc;
            CheckInhibitors();
            Prepare();
        }

        private void CheckInhibitors()
        {
            foreach(Transition t in this.document.PetriModel.Transitions)
            {
                if (this.document.PetriModel.GetIncomingInhibitors(t).Count > 0)
                {
                    String message = "There are some inhibitor arcs in the net. Safety may not be correct!";
                    MessageBox.Show(message, "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void Prepare()
        {

            CoveringTree tree = new CoveringTree();
            tree.Build(this.document.PetriModel.IncidentionMatrix, 
                this.document.PetriModel.GetMarkingVector(),
                this.document.PetriModel);

            FullFill(BoundedLabel, tree.Analysis.Bounded);
            FullFill(SafeLabel, tree.Analysis.Safe);
            FullFill(DeadlockLabel, tree.Analysis.Deadlock);

            if (!tree.Analysis.Deadlock)
            {
                this.DeadlockPanel.Visible = false;
            }
            else
            {
               FormatPath(tree.Analysis.PathToDeadlock);
            }
       
        }

        private void FullFill(Label tb, bool verite)
        {
            if (verite) tb.Text = "TRUE";
            else tb.Text = "FALSE";
        }

        private void FormatPath(ReadOnlyCollection<int> path)
        {
            this.PathTextBox.Text = "";

            if (path.Count > 0)
            {
                for (int i = 0; i < path.Count - 1; i++)
                {
                    this.PathTextBox.Text += this.document.PetriModel.Transitions[path[i]].Name + " -> ";
                }

                this.PathTextBox.Text += this.document.PetriModel.Transitions[path[path.Count - 1]].Name;
            }
            else
            {
                this.PathTextBox.Text += "Net is already in deadlock!";
            }
        }


    }
}